package task;

import com.book.constrains.SystemConstants;
import com.book.pojo.Admin;
import com.book.pojo.Book;
import com.book.pojo.Reader;
import com.book.protocol.Protocol;
import com.book.service.AdminService;
import com.book.service.impl.AdminServiceImpl;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;

public class AdminTaskThread implements Runnable{
    //代表教师的套接字对象
    private Socket adminClient;
    //业务层对象
    private AdminService adminService = new AdminServiceImpl();
    //通信协议对象
    private Protocol<Object> protocol;
    public AdminTaskThread(Socket adminClient,Protocol<Object> protocol) {
        this.adminClient = adminClient;
        this.protocol = protocol;
    }

    @Override
    public void run() {

        while(true) {
            if (null == protocol) {
                try {
                    //后续多次操作，重新获取协议对象
                    ObjectInputStream ois = new ObjectInputStream(adminClient.getInputStream());
                    protocol = (Protocol<Object>) ois.readObject();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
            switch (protocol.getOpt()){
                case SystemConstants.ADMIN_LOGIN://管理员登陆
                    adminLogin();
                    break;
                case SystemConstants.ADMIN_ADD_BOOK://管理员增加图书
                    addBook();
                    break;
                case SystemConstants.ADMIN_DELETE_BOOK://管理员删除图书
                    deleteBook();
                    break;
                case SystemConstants.ADMIN_UPDATE_BOOK://管理员修改图书
                    updateBook();
                    break;
                case SystemConstants.ADMIN_FINDALL_BOOKS://管理员查询图书
                    queryBooks();
                    break;
                case SystemConstants.ADMIN_ADD_READER://管理员添加读者
                    addReader();
                    break;
                case SystemConstants.ADMIN_FINDALL_READERS://管理员删除读者
                    queryReaders();
                    break;
                case SystemConstants.ADMIN_DELETE_READER://管理员修改读者
                    deleteReader();
                    break;


            }
        }
    }

    private void deleteReader() {
        try {
            System.out.println("接收到了删除读者请求！！！！！！！！！");

            // 获取要删除的读者 ID
            int readerId = (int) protocol.getData();
            System.out.println("即将删除的读者 ID: " + readerId);

            // 调用服务层方法删除读者
            boolean isSuccess = adminService.deleteReader(readerId);

            // 创建返回的协议对象
            Protocol<Integer> backProtocol = new Protocol<>();
            if (isSuccess) {
                backProtocol.setCode(SystemConstants.Code.OPT_SUCCESS); // 操作成功
                backProtocol.setMsg("读者删除成功！");
                System.out.println("读者删除成功，ID：" + readerId);
            } else {
                backProtocol.setCode(SystemConstants.Code.OPT_FAILURE); // 操作失败
                backProtocol.setMsg("读者删除失败，可能该读者不存在！");
                System.out.println("读者删除失败，ID：" + readerId);
            }
            backProtocol.setData(readerId); // 返回删除的读者 ID

            // 发送响应协议对象到客户端
            ObjectOutputStream oos = new ObjectOutputStream(adminClient.getOutputStream());
            oos.writeObject(backProtocol);
            oos.flush();
            System.out.println("删除响应已发送至客户端");

            // 清空协议对象，等待下一次操作
            this.protocol = null;
        } catch (IOException e) {
            System.err.println("删除读者过程中出现 IO 错误：" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("删除读者过程中发生异常：" + e.getMessage());
            e.printStackTrace();
        }
    }


    private void queryReaders() {
        try {
            System.out.println("接收到了查询读者请求==========");

            // 调用服务层方法查询所有读者
            List<Reader> readers = adminService.getAllReaders();
            System.out.println("查询到的读者列表：" + readers);
            // 创建返回的协议对象
            Protocol<List<Reader>> backProtocol = new Protocol<>();
            System.out.println("查询到的读者列表：" + readers);
            if (readers != null && !readers.isEmpty()) {
                backProtocol.setCode(SystemConstants.Code.OPT_SUCCESS);
                backProtocol.setMsg("查询成功！");
                backProtocol.setData(readers);
                System.out.println("查询成功，返回读者列表");
            } else {
                backProtocol.setCode(SystemConstants.Code.OPT_FAILURE);
                backProtocol.setMsg("没有找到任何读者信息！");
                System.out.println("查询失败，数据库中无读者记录");
            }

            // 发送响应协议对象到客户端
            ObjectOutputStream oos = new ObjectOutputStream(adminClient.getOutputStream());
            oos.writeObject(backProtocol);
            oos.flush();
            System.out.println("查询响应已发送至客户端");

            // 清空协议对象，等待下一次操作
            this.protocol = null;
        } catch (IOException e) {
            System.err.println("查询读者过程中出现 IO 错误：" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("查询读者过程中发生异常：" + e.getMessage());
            e.printStackTrace();
        }
    }


    private void addReader() {
        try {
            System.out.println("接收到了新增读者请求！！！！！！！！！");

            // 获取传入的读者信息
            Reader reader = (Reader) protocol.getData();
            boolean isSuccess = adminService.addReader(reader);

            // 创建返回的协议对象
            Protocol<Reader> backProtocol = new Protocol<>();
            if (isSuccess) {
                backProtocol.setCode(SystemConstants.Code.OPT_SUCCESS); // 操作成功
                backProtocol.setMsg("读者添加成功！");
                System.out.println("读者添加成功：" + reader.getUsername());
            } else {
                backProtocol.setCode(SystemConstants.Code.OPT_FAILURE); // 操作失败
                backProtocol.setMsg("读者添加失败！");
                System.out.println("读者添加失败：" + reader.getUsername());
            }
            backProtocol.setData(reader);

            // 发送响应协议对象到客户端
            ObjectOutputStream oos = new ObjectOutputStream(adminClient.getOutputStream());
            oos.writeObject(backProtocol);
            oos.flush();
            System.out.println("添加读者响应已发送至客户端");

            // 清空协议对象，等待下一次操作
            this.protocol = null;
        } catch (IOException e) {
            System.err.println("读者添加过程中出现 IO 错误：" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("读者添加过程中发生异常：" + e.getMessage());
            e.printStackTrace();
        }
    }


    private void deleteBook() {
        try {
            System.out.println("接收到了删除请求！！！！！！！！！");

            // 获取要删除的图书 ID
            int id_delete = (int) protocol.getData();
            System.out.println("即将删除的图书 ID: " + id_delete);

            // 调用服务层方法删除图书
            boolean isSuccess = adminService.deleteBook(id_delete);

            // 创建返回的协议对象（类型应该是 Integer）
            Protocol<Integer> backProtocol = new Protocol<>();
            if (isSuccess) {
                backProtocol.setCode(SystemConstants.Code.OPT_SUCCESS); // 操作成功
                backProtocol.setMsg("图书删除成功！");
                System.out.println("图书删除成功，ID：" + id_delete);
            } else {
                backProtocol.setCode(SystemConstants.Code.OPT_FAILURE); // 操作失败
                backProtocol.setMsg("图书删除失败，可能书籍不存在！");
                System.out.println("图书删除失败，ID：" + id_delete);
            }
            backProtocol.setData(id_delete); // 返回删除的图书 ID

            // 发送响应协议对象到客户端
            ObjectOutputStream oos = new ObjectOutputStream(adminClient.getOutputStream());
            oos.writeObject(backProtocol);
            oos.flush();
            System.out.println("删除响应已发送至客户端");

            // 清空协议对象，等待下一次操作
            this.protocol = null;
        } catch (IOException e) {
            System.err.println("图书删除过程中出现 IO 错误：" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("图书删除过程中发生异常：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private void addBook() {
        try {
            System.out.println("接收到了增加请求！！！！！！！！！");
            // 获取传入的图书信息
            Book book = (Book) protocol.getData();
            boolean isSuccess = adminService.addBook(book);

            // 创建返回的协议对象
            Protocol<Book> backProtocol = new Protocol<>();
            if (isSuccess) {
                backProtocol.setCode(SystemConstants.Code.OPT_SUCCESS); // 操作成功
                backProtocol.setMsg("图书添加成功！");
            } else {
                backProtocol.setCode(SystemConstants.Code.OPT_FAILURE); // 操作失败
                backProtocol.setMsg("图书添加失败！");
            }
            backProtocol.setData(book); // 返回添加的图书数据

            // 发送响应协议对象到客户端
            ObjectOutputStream oos = new ObjectOutputStream(adminClient.getOutputStream());
            oos.writeObject(backProtocol);
            oos.flush();

            // 清空协议对象，等待下一次操作
            this.protocol = null;
        } catch (IOException e) {
            throw new RuntimeException("图书添加过程出现错误：" + e.getMessage());
        }
    }

    private void adminLogin() {
        try{
            Admin admin = (Admin) protocol.getData();
            Admin loginAdmin = adminService.login(admin);
            Protocol backProtocol = new Protocol();
            if(null != loginAdmin){
                //登录成功
                backProtocol.setMsg("登录成功！");
                backProtocol.setCode(SystemConstants.Code.OPT_SUCCESS);
            }else {
                //登录失败
                backProtocol.setMsg("登录失败！");
                backProtocol.setCode(SystemConstants.Code.OPT_FAILURE);
            }
            //将封装结果的协议对象发送给客户端
            ObjectOutputStream oos = new ObjectOutputStream(adminClient.getOutputStream());
            oos.writeObject(backProtocol);
            oos.flush();
            //清空协议对象
            this.protocol = null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private void updateBook() {
        try {
            System.out.println("接收到了修改图书请求！！！！！！！！！");

            // 获取传入的图书信息
            Book book = (Book) protocol.getData();
            boolean isSuccess = adminService.updateBook(book);

            // 创建返回的协议对象
            Protocol<Book> backProtocol = new Protocol<>();
            if (isSuccess) {
                backProtocol.setCode(SystemConstants.Code.OPT_SUCCESS); // 操作成功
                backProtocol.setMsg("图书更新成功！");
                System.out.println("图书更新成功，ID：" + book.getId());
            } else {
                backProtocol.setCode(SystemConstants.Code.OPT_FAILURE); // 操作失败
                backProtocol.setMsg("图书更新失败！");
                System.out.println("图书更新失败，ID：" + book.getId());
            }
            backProtocol.setData(book); // 返回更新后的图书数据

            // 发送响应协议对象到客户端
            ObjectOutputStream oos = new ObjectOutputStream(adminClient.getOutputStream());
            oos.writeObject(backProtocol);
            oos.flush();
            System.out.println("更新响应已发送至客户端");

            // 清空协议对象，等待下一次操作
            this.protocol = null;
        } catch (IOException e) {
            System.err.println("图书更新过程中出现 IO 错误：" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("图书更新过程中发生异常：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private void queryBooks() {
        try {


            List<Book> books = adminService.findAllBooks();
            Protocol<String> backProtocol = new Protocol<>();

            if (books != null && !books.isEmpty()) {
                backProtocol.setCode(SystemConstants.Code.OPT_SUCCESS);
                backProtocol.setMsg("查询成功，共找到 " + books.size() + " 本书！");

                // 格式化输出
                StringBuilder result = new StringBuilder();
                result.append("查询到的图书信息如下：\n");
                result.append("--------------------------------------------------\n");
                result.append(String.format("%-5s %-20s %-20s %-10s\n", "ID", "书名", "作者", "可借状态"));
                result.append("--------------------------------------------------\n");
                for (Book book : books) {
                    result.append(String.format("%-5d %-20s %-20s %-10s\n",
                            book.getId(), book.getTitle(), book.getAuthor(), book.isAvailable() ? "可借" : "不可借"));
                }
                result.append("--------------------------------------------------");

                backProtocol.setData(result.toString());
                //System.out.println(result.toString()); // 服务器打印美化后的查询结果
            } else {
                backProtocol.setCode(SystemConstants.Code.OPT_FAILURE);
                backProtocol.setMsg("没有找到任何书籍！");
                backProtocol.setData("暂无书籍信息！");
            }

            // 发送响应
            ObjectOutputStream oos = new ObjectOutputStream(adminClient.getOutputStream());
            oos.writeObject(backProtocol);
            oos.flush();
        } catch (IOException e) {
            System.err.println("查询图书过程中出现 IO 错误：" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("查询图书过程中发生异常：" + e.getMessage());
            e.printStackTrace();
        }
    }

}
